//
//  SqliteHelper.swift
//  app_rn_frontend
//
//  Created by 鱼涛 on 2017/12/12.
//  Copyright © 2017年 Facebook. All rights reserved.
//

import Foundation
import WCDBSwift

public class SQLiteHelper {
    
    static func getDb() -> Database {
        let db = Database(at: AppStatusManager.instance.urlForUserDB ?? URL(string: "localhost")!)
        return db
    }
    
    static func buildUserDatabase(urlForUser: URL, dbName: String) throws {
        let urlForUserDB = urlForUser.appendingPathComponent(dbName, isDirectory: false)
        print(urlForUser)
        let db = Database(at: urlForUserDB.path)
        
        try db.create(table: Contact.table, of: Contact.self)
        try db.create(table: Group.table, of: Group.self)
        try db.create(table: Message.table, of: Message.self)
        try db.create(table: SchemaVersion.table, of: SchemaVersion.self)
        try db.create(table: Session.table, of: Session.self)
        try db.create(table: SessionMember.table, of: SessionMember.self)
        try db.create(table: GroupMember.table, of: GroupMember.self)
        
        let appVersion:String = Bundle.main.infoDictionary!["CFBundleVersion"] as? String ?? ""
        let appName = "tingmimi"
        var dbVersion = ""
        var schema:SchemaVersion
        if let schemaInDb:SchemaVersion = try db.getObject(on: SchemaVersion.CodingKeys.all, fromTable: SchemaVersion.table,where:SchemaVersion.CodingKeys.tableName == appName) {
            dbVersion = schemaInDb.tableVersion ?? ""
            schema = schemaInDb
            schema.tableVersion = appVersion
            try db.update(table: SchemaVersion.table, on: SchemaVersion.CodingKeys.all, with: schema,where:SchemaVersion.CodingKeys.tableName == appName)
        } else {
            schema = SchemaVersion()
            schema.tableVersion = appVersion
            schema.tableName = appName
            try db.insert(schema, intoTable: SchemaVersion.table)
        }
        switch dbVersion {
        case "":
            try db.run(transaction: { _ in
                let msgs: [Message] = try db.getObjects(on: Message.CodingKeys.all, fromTable: Message.table)
                for msg in msgs {
                    if !msg.createdDatetime.isEmpty {
                        let createTime = TimeUtil.instance.date(msg.createdDatetime)
                        msg.createTime = createTime
                        msg.ts = createTime
                        try db.insertOrReplace(msg, intoTable: Message.table)
                    }
                }
            })
        case "1.9.14":
            let contact = Contact()
            try db.run(transaction: { _ in
                try db.update(table: Contact.table, on: [Contact.CodingKeys.remarkName], with: contact)
            })
        default:
            return
        }
        
    }
}
